/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package manager;

import calendar.EventLink;
import entity.Event;
import entity.Invitation;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import entity.RegisteredUser;
import java.util.List;
import entity.enumeration.EventStatus;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import utils.HashGenerator;

/**
 *
 * @author Stefan Martinov <stefan.martinov@gmail.com>
 */
public class EventManager extends DefaultManager<Event> {

    public EventManager() {
        super(Event.class);
    }

    public List<Event> getUserInvitedEvents(RegisteredUser user) {
        EntityManager em = getEntityManager();
        String query = "SELECT x.event FROM Invitation x WHERE x.contact.email = ?1 AND x.event.status =?2 AND x.deleted = false";
        Query q = em.createQuery(query);
        q.setParameter(1, user.getEmail());
        q.setParameter(2, EventStatus.Active);
        List<Event> events = q.getResultList();

        em.close();
        return events;
    }

    public List<Event> getUserEvents(RegisteredUser user) {
        EntityManager em = getEntityManager();
        String query1 = "SELECT x FROM Event x WHERE x.registeredUser = ?1 AND ( not x.status = ?2 ) AND x.deleted = 0";
        Query q = em.createQuery(query1);
        q.setParameter(1, user);
        q.setParameter(2, EventStatus.Canceled);


        List<Event> events = q.getResultList();

        em.close();
        return events;
    }

    public static void main(String[] args) {
        RegisteredUserManager rum = new RegisteredUserManager();
        EventManager evm = new EventManager();
        RegisteredUser ru = rum.findByID(new Long(2));
    }

    public List<EventLink> getUserEventsForDay(RegisteredUser user, Date date) {
        List<EventLink> links = new ArrayList<EventLink>();
        //To remove duplicates
        Set<Long> idSets = new HashSet<Long>();
        EntityManager em = getEntityManager();
        Calendar start_date = Calendar.getInstance();
        Calendar end_date = Calendar.getInstance();
        start_date.setTime(date);
        end_date.setTime(date);
        // 00:00
        start_date.set(Calendar.HOUR_OF_DAY, 0);
        start_date.set(Calendar.MINUTE, 0);
        start_date.set(Calendar.SECOND, 0);
        //23:59
        end_date.set(Calendar.HOUR_OF_DAY, 23);
        end_date.set(Calendar.MINUTE, 59);
        end_date.set(Calendar.SECOND, 59);
        String query = "SELECT x FROM Invitation x WHERE x.contact.email = ?1 AND not x.event.status = ?2 AND x.deleted = 0 AND x.event.startTime >= ?3 AND x.event.startTime <= ?4";
        Query q = em.createQuery(query);
		
        q.setParameter(1, user.getEmail());
        q.setParameter(2, EventStatus.Canceled);
        q.setParameter(3, start_date.getTime());
        q.setParameter(4, end_date.getTime());

        for (Invitation i : (List<Invitation>) q.getResultList()) {
            EventLink el = new EventLink();
            el.setLink("event/event_display.faces?eventId=" + i.getEvent().getId() + "&contactId="
                    + i.getContact().getId() + "&code=" + HashGenerator.generateHash(i.getContact().getEmail()));
            el.setName(i.getEvent().getName());
            //Since duplicates can only occur between invitations and events

            idSets.add(i.getEvent().getId());
        }
		
        query = "SELECT x FROM Event x WHERE x.registeredUser = ?1 AND not x.status = ?2 AND x.deleted = 0 AND x.startTime >= ?3 AND x.startTime <= ?4";
        q = em.createQuery(query);
        q.setParameter(1, user);
        q.setParameter(2, EventStatus.Canceled);
        q.setParameter(3, start_date.getTime());
        q.setParameter(4, end_date.getTime());

        for (Event e : (List<Event>) q.getResultList()) {
            EventLink el = new EventLink();
            el.setLink("event/event_display.faces?eventId=" + e.getId() + "&contactId=0");
            el.setName(e.getName());
            //No duplicates can be found here
            if (!idSets.contains(e.getId())) {
                links.add(el);
            }
        }
        //Filter out duplicate events
        em.close();
        return links;
    }

    /**
     * Check if the event has passed , and update it if it passed
     * @param event
     * @return true if it is active or false if it is canceled or passed
     */
    public boolean checkStatusAndUpdateEvent(Event event) {
        Date now = Calendar.getInstance().getTime();
        if (event.getStatus().equals(EventStatus.Active)) {
            Date comparison = event.getStartTime();
            if (event.getResponseTime() != null) {
                comparison = event.getResponseTime();
            }
            if (now.after(comparison)) {
                event.setStatus(EventStatus.Finished);
                edit(event);
            } else {
                return true;
            }


        }
        return false;
    }
}
